using System;
using HawkAuthentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;

namespace housingsafety.server.Hawk
{
    public static class HawkAuthenticationExtensions
    {
        public static AuthenticationBuilder AddHawk(this AuthenticationBuilder builder)
        {
            return builder.AddHawk(HawkConstants.AuthenticationScheme, options => { });
        }

        public static AuthenticationBuilder AddHawk(
            this AuthenticationBuilder builder,
            Action<HawkAuthenticationOptions> configuration)
        {
            return builder.AddHawk(HawkConstants.AuthenticationScheme, configuration);
        }

        public static AuthenticationBuilder AddHawk(
            this AuthenticationBuilder builder, string scheme,
            Action<HawkAuthenticationOptions> configuration)
        {
            if (builder == null)
            {
                throw new NullReferenceException(nameof(builder));
            }

            builder.Services.Configure(configuration);

            builder.Services.AddSingleton<
                IPostConfigureOptions<JwtBearerOptions>,
                JwtBearerOptionsPostConfiguration>();

            return builder;
        }

        public static IApplicationBuilder UseHawk(
            this IApplicationBuilder builder)
        {

            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }

            return builder.UseMiddleware<HawkMiddleware>();
        }
    }
}
